package com.ys.utils.help;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ys.base.BaseConstants;
import com.ys.utils.base.http.McodeHandler;
import com.ys.utils.base.j2se.DateUtil;
import com.ys.utils.base.j2se.JsonUtil;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.GroupKey;
import com.ys.utils.redis.key.UserKey;
import com.ys.utils.spring.config.SystemError;
import com.ys.utils.spring.properties.Config;
import com.ys.web.user.friends.po.BaseGroupInfoPO;
import com.ys.web.user.friends.po.BaseUserFriendsPO;
import com.ys.web.user.login.LoginInfo;
import com.ys.web.user.login.LoginResult;
import com.ys.web.user.login.LoginService;
import com.ys.web.ws.bean.MessageRequestBean;
import com.ys.web.ws.bean.MessageResponseBean;
import com.ys.web.ws.send.po.GChatPO;
import com.ys.web.ws.send.po.SChatPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author quxinjun
 * @version 1.0.0
 * @ClassName UserUtils.java
 * @Description UserUtils
 * @createTime 2021年05月12日 13:48:00
 */
@Slf4j
@Component
public class UserUtils {

    private static final String SYSTEM_HEAD = "https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2993836181,3668684044&fm=26&gp=0.jpg";

    public static final BaseUserFriendsPO CLIENT = new BaseUserFriendsPO();
    public static final BaseUserFriendsPO ASSISTANT = new BaseUserFriendsPO();
    public static final BaseUserFriendsPO SYS_NOTICE = new BaseUserFriendsPO();
    @Autowired
    private LoginService loginService;

    private static LoginService loginServer;

    static {
        CLIENT.setUserId(McodeHandler.to32Radix(BaseConstants.ClientConstants.CLIENT_ID));
        CLIENT.setNickName(BaseConstants.ClientConstants.CLIENT_NICK_NAME);
        CLIENT.setAvatarUrl(BaseConstants.ClientConstants.CLIENT_HEAD_IMG);
        CLIENT.setGender(BaseConstants.ClientConstants.CLIENT_GENDER);
        CLIENT.setFriendId(McodeHandler.to32Radix(BaseConstants.ClientConstants.CLIENT_ID));


        ASSISTANT.setUserId(McodeHandler.to32Radix(BaseConstants.ClientConstants.ASSISTANT_ID));
        ASSISTANT.setNickName(BaseConstants.ClientConstants.ASSISTANT_NICK_NAME);
        ASSISTANT.setAvatarUrl(BaseConstants.ClientConstants.ASSISTANT_HEAD_IMG);
        ASSISTANT.setGender(BaseConstants.ClientConstants.CLIENT_GENDER);
        ASSISTANT.setFriendId(McodeHandler.to32Radix(BaseConstants.ClientConstants.ASSISTANT_ID));

        SYS_NOTICE.setNickName(BaseConstants.ClientConstants.SYS_NOTICE_NICK_NAME);
        SYS_NOTICE.setAvatarUrl(BaseConstants.ClientConstants.SYS_NOTICE_HEAD_IMG);
    }

    public static LoginResult getLoginResult() {
        LoginResult loginResult = new LoginResult();
        loginResult.setFlag(false);
        loginResult.setPhone(Config.pp.get("freeze.tip.phone"));
        loginResult.setPhoneDesc(Config.pp.get("freeze.tip.phone.desc"));
        loginResult.setQq(Config.pp.get("freeze.tip.qq"));
        loginResult.setQqDesc(Config.pp.get("freeze.tip.qq.desc"));
        return loginResult;
    }

    public static void validateUserAccountStatus(String uid) {
        if(!StringHandler.getString(BaseConstants.ClientConstants.CLIENT_ID).equals(uid)){
            LoginInfo loginInfo = loginServer.infoByUid(uid);
            if (loginInfo.getAccountStatus() == 1) {
                SystemError.wrapBs("500", "您的账号已注销，操作失败");
            }
            if (loginInfo.getAccountStatus() == 2) {
                SystemError.wrapBs("500", "您的账号已禁用，操作失败");
            }
        }
    }

    @PostConstruct
    public void init() {
        loginServer = this.loginService;
    }

    /**
     * @title getCacheUser
     * @description 通过用户id  获取用户用户缓存中的信息
     * @author quxinjun
     * @updateTime 2021/5/12 13:49
     * @return: com.ys.web.user.login.LoginInfo
     */
    public static LoginInfo getCacheUser(Object uid) {
//        Map<Object, Object> map = Redis.hash.hgetall(UserKey.userInfoByUid(uid));
        return loginServer.infoByUid(String.valueOf(uid));
    }


    /**
     * @param fromId  发送人
     * @param groupId 组id
     * @param code    消息类型
     * @param data    数据
     * @title getMessageResponse
     * @description 组装数据(返回对象集合json)
     * @author quxinjun
     * @updateTime 2021/5/12 16:03
     * @return: java.lang.String
     */
    public static String getMessageResponseList(String fromId, String groupId, Integer code, String data, String createTime) {
        LoginInfo cacheUser = getCacheUser(fromId);
        List<MessageResponseBean> list = new ArrayList<>();
        MessageResponseBean messageResponseBean = new MessageResponseBean();

        messageResponseBean.setMessageId(IdUtil.simpleUUID());
        messageResponseBean.setFrom(McodeHandler.to32Radix(Long.parseLong(fromId)));
        messageResponseBean.setUserName(fromId.equals(BaseConstants.SYSTEM_OBJECT_VALUE) ? BaseConstants.ClientConstants.CLIENT_NICK_NAME : getCacheUserNickName(groupId, fromId, cacheUser.getNickName()));
        messageResponseBean.setAvatarUrl(fromId.equals(BaseConstants.SYSTEM_OBJECT_VALUE) ? BaseConstants.ClientConstants.CLIENT_HEAD_IMG : cacheUser.getAvatarUrl());
        messageResponseBean.setCreateTime(createTime == null ? DateUtil.getDate(new Date(), BaseConstants.BASE_FORMAT) : createTime);
        messageResponseBean.setCode(code);
        messageResponseBean.setGroupId(groupId);
        messageResponseBean.setGroupName(getGroupCacheNameByGroupId(groupId));
        messageResponseBean.setWindowId(groupId != null ? BaseConstants.GROUP_PREFIX + groupId : BaseConstants.SINGLE_PREFIX + McodeHandler.to32Radix(Long.parseLong(fromId)));
        messageResponseBean.setGroupPic(groupId != null ? (StringHandler.isNotEmpty(GroupUtils.getCacheGroupInfo(groupId)) ? GroupUtils.getCacheGroupInfo(groupId).getPic() : null) : null);
        messageResponseBean.setData(data);
        list.add(messageResponseBean);
        return JsonUtil.toJson(list);
    }

    /**
     * @param fromId  发送人
     * @param groupId 组id
     * @param code    消息类型
     * @param data    数据
     * @title getMessageResponse
     * @description 组装数据（返回消息对象）
     * @author quxinjun
     * @updateTime 2021/5/13 17:07
     * @return: com.ys.web.ws.bean.MessageResponseBean
     */
    public static MessageResponseBean getMessageResponse(String fromId, String groupId, Integer code, String data, String createTime, Double width, Double height) {
        LoginInfo cacheUser = getCacheUser(fromId);
        MessageResponseBean messageResponseBean = new MessageResponseBean();
        messageResponseBean.setMessageId(IdUtil.simpleUUID());
        messageResponseBean.setFrom(McodeHandler.to32Radix(Long.parseLong(fromId)));
        messageResponseBean.setUserName(fromId.equals(BaseConstants.SYSTEM_OBJECT_VALUE) ? BaseConstants.ClientConstants.CLIENT_NICK_NAME : getCacheUserNickName(groupId, fromId, cacheUser.getNickName()));
        messageResponseBean.setAvatarUrl(fromId.equals(BaseConstants.SYSTEM_OBJECT_VALUE) ? BaseConstants.ClientConstants.CLIENT_HEAD_IMG : cacheUser.getAvatarUrl());
        messageResponseBean.setCreateTime(createTime == null ? DateUtil.getDate(new Date(), BaseConstants.BASE_FORMAT) : createTime);
        messageResponseBean.setCode(code);
        messageResponseBean.setGroupId(groupId);
        messageResponseBean.setGroupName(getGroupCacheNameByGroupId(groupId));
        messageResponseBean.setWindowId(groupId != null ? BaseConstants.GROUP_PREFIX + groupId : BaseConstants.SINGLE_PREFIX + McodeHandler.to32Radix(Long.parseLong(fromId)));
        messageResponseBean.setGroupPic(groupId != null ? GroupUtils.getCacheGroupInfo(groupId).getPic() : null);
        messageResponseBean.setHeight(height);
        messageResponseBean.setWidth(width);
        messageResponseBean.setData(data);
        return messageResponseBean;
    }


    /**
     * @param messageRequestBean socket 消息请求对象
     * @title getMessageResponse
     * @description 组装数据
     * @author quxinjun
     * @updateTime 2021/5/12 16:02
     * @return: java.lang.String
     */
    public static String getMessageResponseList(MessageRequestBean messageRequestBean, String windowPrefix) {
        MessageResponseBean messageResponseBean = new MessageResponseBean();
        LoginInfo cacheUser = getCacheUser(McodeHandler.from32Radix(messageRequestBean.getFrom()));
        List<MessageResponseBean> list = new ArrayList<>();
        messageResponseBean.setMessageId(messageRequestBean.getMessageId());
        messageResponseBean.setFrom(McodeHandler.to32Radix(Long.parseLong(BaseConstants.SYSTEM_OBJECT_VALUE)).equals(messageRequestBean.getFrom()) ? CLIENT.getUserId() : messageRequestBean.getFrom());
        messageResponseBean.setUserName(McodeHandler.to32Radix(Long.parseLong(BaseConstants.SYSTEM_OBJECT_VALUE)).equals(messageRequestBean.getFrom()) ? BaseConstants.ClientConstants.CLIENT_NICK_NAME : cacheUser.getNickName());
        messageResponseBean.setAvatarUrl(McodeHandler.to32Radix(Long.parseLong(BaseConstants.SYSTEM_OBJECT_VALUE)).equals(messageRequestBean.getFrom()) ? BaseConstants.ClientConstants.CLIENT_HEAD_IMG : cacheUser.getAvatarUrl());
        messageResponseBean.setCreateTime(messageRequestBean.getCreateTime());
        messageResponseBean.setCode(messageRequestBean.getCode());
        messageResponseBean.setGroupId(messageRequestBean.getGroupId());
        messageResponseBean.setGroupName(getGroupCacheNameByGroupId(messageRequestBean.getGroupId()));
        messageResponseBean.setGroupPic(messageRequestBean.getGroupId() != null ? GroupUtils.getCacheGroupInfo(messageRequestBean.getGroupId()).getPic() : null);
        messageResponseBean.setWidth(messageRequestBean.getWidth());
        messageResponseBean.setHeight(messageRequestBean.getHeight());
        messageResponseBean.setData(messageRequestBean.getData());
        if (StringHandler.isNotEmpty(windowPrefix)) {
            messageResponseBean.setWindowId(
                    (StringHandler.isNotEmpty(messageRequestBean.getGroupId()) ? BaseConstants.GROUP_PREFIX + messageRequestBean.getGroupId() : BaseConstants.SINGLE_PREFIX + messageRequestBean.getFrom()));
        }

        //组装图片
        list.add(messageResponseBean);
        return JsonUtil.toJson(list);
    }

    /**
     * 组装消息实体
     *
     * @param messageRequestBean
     * @return
     */
    public static SChatPO getSChatPO(MessageRequestBean messageRequestBean) {
        long fromId = McodeHandler.from32Radix(messageRequestBean.getFrom());
        long to = McodeHandler.from32Radix(messageRequestBean.getTo());
        long tableSuffix = to % BaseConstants.sChatTableNum;

        SChatPO sChatPO = new SChatPO();

        sChatPO.setTableName(BaseConstants.S_TABLE_PREFIX + tableSuffix);
        sChatPO.setFromId(fromId);
        sChatPO.setToId(to);
        sChatPO.setMessageId(messageRequestBean.getMessageId());
        sChatPO.setCode(messageRequestBean.getCode());
        sChatPO.setData(messageRequestBean.getData());
        sChatPO.setFromName(messageRequestBean.getUserName());
        sChatPO.setFromAvatarUrl(messageRequestBean.getAvatarUrl());
        sChatPO.setCreateTime(messageRequestBean.getCreateTime());
        sChatPO.setWidth(messageRequestBean.getWidth());
        sChatPO.setHeight(messageRequestBean.getHeight());
        sChatPO.setSoundSeconds(messageRequestBean.getSoundSeconds());
        sChatPO.setIsSuccess(false);
        return sChatPO;
    }

    /**
     * 组装群消息对象
     *
     * @param messageRequestBean
     * @return
     */
    public static GChatPO getGChatPO(MessageRequestBean messageRequestBean) {
        long fromId = McodeHandler.from32Radix(messageRequestBean.getFrom());
        long to = Long.parseLong(messageRequestBean.getGroupId());
        long tableSuffix = to % BaseConstants.gChatTableNum;

        GChatPO gChatPO = new GChatPO();
        gChatPO.setTableName(BaseConstants.G_TABLE_PREFIX + tableSuffix);
        gChatPO.setFrom(fromId);
        gChatPO.setTo(to);
        gChatPO.setMessageId(messageRequestBean.getMessageId());
        gChatPO.setCode(messageRequestBean.getCode());
        gChatPO.setData(messageRequestBean.getData());
        gChatPO.setFromName(messageRequestBean.getUserName());
        gChatPO.setFromAvatarUrl(messageRequestBean.getAvatarUrl());
        gChatPO.setWidth(messageRequestBean.getWidth());
        gChatPO.setHeight(messageRequestBean.getHeight());
        gChatPO.setSoundSeconds(messageRequestBean.getSoundSeconds());
        gChatPO.setToMembers(messageRequestBean.getToMembers());
        gChatPO.setCreateTime(messageRequestBean.getCreateTime());
        return gChatPO;
    }


    /**
     * @param groupId         组id
     * @param fromId          发送人id
     * @param currentNickName 当前发送人缓存名称
     * @title getCacheUserNickName
     * @description
     * @author quxinjun
     * @updateTime 2021/5/18 21:18
     * @return: java.lang.String
     */
    public static String getCacheUserNickName(String groupId, String fromId, String currentNickName) {
//        if (StringHandler.isEmpty(groupId)) {
        return currentNickName;
//        }
//        String groupCacheName = (String) Redis.hash.hGet(GroupKey.groupUserGroupRemarkKey(groupId), fromId);
//        return StringHandler.isEmpty(groupCacheName) ? currentNickName : groupCacheName;
    }

    /**
     * 记录用户最后一次退出使用的时间
     *
     * @param uid
     */
    public static void lastLogoutTime(Object uid) {
        String loginTimeKey = UserKey.userLoginTimeByUid();
        Redis.hash.hSet(loginTimeKey, String.valueOf(uid), uid + ":" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
    }

    public static String getGroupCacheNameByGroupId(String groupId) {
        if (StringHandler.isNotEmpty(groupId)) {
            String groupKey = GroupKey.groupInfoKey(groupId);
            if (Redis.key.exists(groupKey)) {
                String groupInfoStr = Redis.str.get(groupKey);
                if (StringHandler.isNotEmpty(groupInfoStr)) {
                    BaseGroupInfoPO baseGroupInfoPO = JsonUtil.jsonToBean(groupInfoStr, BaseGroupInfoPO.class);
                    Long size = Redis.zSet.size(GroupKey.groupMembersKey(groupId));
//                    return baseGroupInfoPO.getName() + "(" + size + ")";
                    return baseGroupInfoPO.getName();
                }
            } else {
                return loginServer.getGroupNameAndSize(groupId);
            }
        }
        return null;
    }

}
